import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/user';
import { useNavbarStore } from '../store/navbar';
import DashboardView from '../views/DashboardView.vue'
import PetsShoppingView from "../views/PetsShoppingView.vue"
import UserPageView from "../views/UserPageView.vue";
import ShoppingCart from "../views/ShoppingCart.vue"

/**
 * title: 页面标题
 * requiresAuth: 是否需要登录
 * roles: 可以进入页面的角色
*/
const routes = [
  {
    path: '/',
    name: 'Dashboard',
    component: DashboardView,
    meta: {
      title: '首页',
      requiresAuth: false,
    }
  },
  {
    path: '/shopping',
    name: 'PetsShopping',
    component: PetsShoppingView,
    meta: {
      title: '宠物商店',
      requiresAuth: false,
    }
  },
  {
    path: '/userinfo',
    name: 'UserInfo',
    component: UserPageView,
    meta: {
      title: '用户信息',
      requiresAuth: true,
    }
  },
  {
    path: '/goods/detail/:id',
    name: 'GoodsDetail',
    component: ()=>import('../views/DetailView/index.vue'),
    meta: {
      title: '产品信息',
      requiresAuth: false,
    }
  },
  {
    path: '/PayOrder',
    name: 'PayOrder',
    component: ()=>import('../views/NowOrder.vue'),
    meta: {
      title: '订单支付页面',
      requiresAuth: false,
    }
  },
  {
    path: '/cart',
    name: 'ShoppingCart',
    component: ShoppingCart,
    meta: {
      title: '购物车',
      requiresAuth: false,
    }
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  // scrollBehavior(to, from, savedPosition) {
  //   return savedPosition || { left: 0, top: 0 }
  // }
})

// /**
//  * 路由守卫，在进入下一个页面之前进行调用
//  */
router.beforeEach((to, from, next) => {
  const userStore= useUserStore()
  const navbarStore = useNavbarStore()
  if(to.meta.requiresAuth && !userStore.isLogin) {
    navbarStore.setActiveMenu(from.path)
    userStore.$patch({
        modalVisible: true
    })
    next(from)
  } else {
    navbarStore.setActiveMenu(to.path);
    if (to.path !== '/') navbarStore.setDropmenuVisible(true)
    else navbarStore.setDropmenuVisible(false)
    next()
  }
})

export default router